/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.borui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MMHCommonUtils {

    /**
     * 返回字体
     *
     * @param width
     * @param textSize
     * @param title
     * @return
     */
    public static float getTextSize(int width, float textSize, String title) {

        float returnTextSize = textSize;

        Paint paint = new Paint();
        paint.setTextSize(textSize);
        int textwidth = (int) paint.measureText(title);
        if (width > textwidth) {
            return returnTextSize;
        } else {

        }

        return returnTextSize;
    }

    /**
     * 获取文字的宽度
     *
     * @param context
     * @param text
     * @param textSize
     * @return
     */
    private static float getTextWidth(Context context, String text, int textSize) {
        TextPaint paint = new TextPaint();
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        paint.setTextSize(scaledDensity * textSize);
        return paint.measureText(text);
    }

    /**
     * unicode转Emoji表情
     *
     * @return
     */
    private String getEmojiStringByUnicode() {
        int unicodeJoy = 0x1F602;
        return new String(Character.toChars(unicodeJoy));
    }

    public static String getWan(int strstest) {

        String strs = strstest + "";
        if (strstest >= 10000l) {
            String sssss = strs.substring(0, strs.length() - 3);
            System.out.println(sssss.subSequence(0, sssss.length() - 1));
            System.out.println(sssss.subSequence(sssss.length() - 1,
                    sssss.length()));

            if (sssss.subSequence(sssss.length() - 1, sssss.length()).equals(
                    "0")) {
                return sssss.subSequence(0, sssss.length() - 1) + "万";
            } else {
                return sssss.subSequence(0, sssss.length() - 1) + "."
                        + sssss.subSequence(sssss.length() - 1, sssss.length())
                        + "万";
            }
        } else {
            return strs;

        }

    }

    /****
     * 统一管理 关于价格的显示 带前缀¥
     *
     * @param price
     * @return
     */
    public static String getPriceFormat(float price) {
        return new StringBuilder("¥").append(
                new java.text.DecimalFormat("#.##").format(price)).toString();
    }

    public static String getPriceFormat(double price) {
        return new StringBuilder("¥").append(
                new java.text.DecimalFormat("#.##").format(price)).toString();
    }

    public static String getPriceFormatNo¥(double price) {
        return new StringBuilder("").append(
                new java.text.DecimalFormat("#.##").format(price)).toString();
    }

    public static String getPriceFormatClean(float price) {
        return new java.text.DecimalFormat("#.##").format(price);
    }

    public static String getDisanceLenght(float price) {
        return new java.text.DecimalFormat("#.#").format(price);
    }

    public static String getPriceFormatClean(double price) {
        return new java.text.DecimalFormat("#.##").format(price);
    }

    public static double get2BigDecale(double doubles) {
        BigDecimal c = new BigDecimal(doubles);
        BigDecimal d = c.setScale(2, BigDecimal.ROUND_HALF_UP);
        return d.doubleValue();
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static int getGridViewHeight(GridView mGridView) {
        ListAdapter listAdapter = mGridView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, mGridView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        return totalHeight;
    }

    /**
     * 验证邮箱地址是否正确
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param mobiles
     * @return [0-9]{5,9}
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isMobile(String mobiles) {
        if (isFixedPhone(mobiles)) {
            return true;
        }
        if (isMobileNO(mobiles)) {
            return true;
        }
        return false;
    }

    /**
     * 区号+座机号码+分机号码
     *
     * @param fixedPhone
     * @return
     */
    public static boolean isFixedPhone(String fixedPhone) {
        String reg = "(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|" +
                "(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)";
        return Pattern.matches(reg, fixedPhone);
    }

    /**
     * 验证座机号
     *
     * @param tell
     * @return
     */
    public static boolean isTell(String tell) {
        boolean flag;
        try {
            //带区号
            Pattern p = Pattern.compile("^0[0-9]{2,4}-[0-9]{7,8}$");
            Matcher m = p.matcher(tell);
            flag = m.matches();
            if (!flag) {
                //不带区号的
                Pattern p1 = Pattern.compile("[0-9]{7,8}$");
                Matcher m1 = p1.matcher(tell);
                flag = m1.matches();
            }
//            if (!flag){
//                //带区号 不带 - 的
//                Pattern p2 = Pattern.compile("^0[0-9]{2,4}[0-9]{7,8}$");
//                Matcher m2 = p2.matcher(tell);
//                flag = m2.matches();
//            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null)
            return runningTaskInfos.get(0).topActivity.getClassName();
        else
            return "";
    }

    /**
     * 根据资源ID获得drawable对象
     *
     * @param mcontext
     * @param resid
     * @return
     */
    public static Drawable GetDrawable(Context mcontext, int resid) {
        Drawable drawable = mcontext.getResources().getDrawable(resid);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        return drawable;
    }

    /**
     * 当前版本
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        String version = "";
        try {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
        }
        return version;
    }

    /**
     * 当前版本号
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        int version = 1;
        try {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
        }
        return version;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 得到手机屏幕宽高数组
     */
    public static int[] getScreenSize(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
        int[] xy = new int[]{screenWidth, screenHeigh};
        return xy;
    }

    /**
     * 获取屏幕宽度
     */
    @SuppressWarnings("deprecation")
    public static int getScreenWidth(Context context) {
        Display display = ((WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 获取屏幕宽度
     */
    public static int getImageHightBySize(Context context, int width, int hight) {
        return (getScreenWidth(context) * hight) / width;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftInput(Context ctx) {
        if (ctx != null) {
            InputMethodManager imm = ((InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE));
            View view = ((Activity) ctx).getCurrentFocus();
            if (view != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 显示软键盘
     */
    public static void showSoftInput(Context ctx, View view) {
        // InputMethodManager.SHOW_FORCED);
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 由参数生成json格式的字符串
     *
     * @param keys
     * @param values
     * @return
     */
    public static String getJsonStr(String[] keys, Object[] values) {
        JSONObject json = new JSONObject();
        try {
            for (int i = 0; i < keys.length; i++) {
                if (values[i] instanceof String) {
                    if (!TextUtils.isEmpty((String) values[i]))
                        json.put(keys[i], values[i]);
                } else
                    json.put(keys[i], values[i]);
            }

        } catch (JSONException e) {
        }

        return json.toString();
    }
    /**
     * 验证用户名 是否合法
     *
     * @param username
     * @return
     */
    public static boolean isUserName(String username) {
        Pattern p = Pattern.compile("/^[\\u4e00-\\u9fa5]{2,5}$/");
        Matcher m = p.matcher(username);
        return m.matches();
    }

    /**
     * 得到状态栏的高度
     *
     * @param activity
     * @return
     */
    public static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass
                        .getField("status_bar_height").get(localObject)
                        .toString());
                statusHeight = activity.getResources()
                        .getDimensionPixelSize(i5);
            } catch (Exception e) {

            }
        }
        return statusHeight;
    }

    /**
     * 得到图片缩略图
     */
    public static Bitmap getImageThumbnail(String imagePath, int width,
                                           int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /**
     * 打电话
     *
     * @param phoneNum
     */
    public static void makeCall(Context context, String phoneNum) {
        // TODO 向IM功能跳转
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phoneNum));
        context.startActivity(intent);
    }

    /***
     * 跳转拨号界面
     *
     * @param context
     * @param phoneNum
     */
    public static void readyCall(Context context, String phoneNum) {
        // TODO 跳转拨号界面
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                + phoneNum));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param imgRescouce
     * @return
     */
    public static Bitmap getImageSpan(Context context,
                                      int imgRescouce) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                imgRescouce);

        return bitmap;
    }

    /**
     * 解析errorMessage
     *
     * @param response
     * @return
     */
    public static String getErrorMessage(String response) {
        String errorMessage = "";
        try {
            JSONObject json = new JSONObject(response);
            errorMessage = json.getString("error");
        } catch (JSONException e) {
        }
        return errorMessage;
    }

    /**
     * 带删除线的价格显示
     *
     * @param tv
     * @param oriPrice 原价
     * @param newPrice 新价
     * @param control  是否控制显示隐藏
     */
    public static void setOriginalPrice(TextView tv, float oriPrice,
                                        float newPrice, boolean control) {
        if (oriPrice > newPrice) {
            if (control)
                tv.setVisibility(View.VISIBLE);
            tv.setText(getPriceFormat(oriPrice));
            tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else if (control)
            tv.setVisibility(View.GONE);
    }


    /**
     * 整数(秒数)转换为时分秒格式(xx:xx:xx)
     *
     * @param time
     * @return
     */
    public static String secToTime(int time) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        StringBuilder timeStr = new StringBuilder();
        minute = time / 60;
        if (minute < 60) {
            second = time % 60;
            timeStr.append(unitFormat(minute)).append(":")
                    .append(unitFormat(second));
        } else {
            hour = minute / 60;
            if (hour > 99)
                return "99:59:59";
            minute = minute % 60;
            second = time - hour * 3600 - minute * 60;
            timeStr.append(unitFormat(hour)).append(":")
                    .append(unitFormat(minute)).append(":")
                    .append(unitFormat(second));
        }
        return timeStr.toString();
    }

    public static String unitFormat(int i) {
        StringBuilder retStr = new StringBuilder();
        if (i >= 0 && i < 10)
            retStr.append("0").append(Integer.toString(i));
        else
            retStr.append(i);
        return retStr.toString();
    }

    /***
     * 正常使用被屏蔽的 url
     */
    public static final String LOCALAPKNAME = "mamahao";

    public static String getLocalApkName(Context context) {
        return LOCALAPKNAME + "V" + (getAppVersionCode(context) + 1) + ".apk";
    }

    public static File getDirectory(Context context, boolean preferExternal) {
        String externalStorageState;
        File appCacheDir = null;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException e) {
            externalStorageState = "";
        }
        if ((preferExternal) && ("mounted".equals(externalStorageState))
                && (hasExternalStoragePermission(context))) {
            appCacheDir = getExternalCacheDir(context, "Exception");
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getPackageName()
                    + "/Exception/";
            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    public static File getDirectory(Context context, boolean preferExternal,
                                    String filename) {
        String externalStorageState;
        File appCacheDir = null;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException e) {
            externalStorageState = "";
        }
        if ((preferExternal) && ("mounted".equals(externalStorageState))
                && (hasExternalStoragePermission(context))) {
            appCacheDir = getExternalCacheDir(context, filename);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getPackageName()
                    + "/" + filename + "/";
            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context, String fileName) {
        File dataDir = new File(new File(
                Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(
                new File(dataDir, context.getPackageName()), fileName);
        if (!(appCacheDir.exists())) {
            if (!(appCacheDir.mkdirs())) {
                return null;
            }
            try {
                new File(appCacheDir, ".nomedia").createNewFile();
            } catch (IOException e) {
            }
        }
        return appCacheDir;
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context
                .checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
        return (perm == 0);
    }
    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 转换类型
     *
     * @param str
     * @return
     */
    public static long passLong(String str) {
        if (str != null && !"".equals(str) && !"null".equals(str)) {
            try {
                Long longTime = Long.parseLong(str);
                return longTime;
            } catch (Exception e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /***
     * 获取状态栏高度
     *
     * @return
     */
    public static int getStatusBar(Context mContext) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = mContext.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }

    /**
     * 转换类型
     *
     * @param str
     * @return
     */
    public static double passDouble(String str) {
        if (str != null && !"".equals(str) && !"null".equals(str)) {
            try {
                Double doubleStr = Double.parseDouble(str);
                return doubleStr;
            } catch (Exception e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 得到安装子手机上的所有应用程序信息 微信包名:"com.tencent.mm"
     *
     * @return
     */
    public static boolean checkInstalledApp(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> packageInfos = pm.getInstalledPackages(0);
        for (PackageInfo pki : packageInfos) {
            // 启动程序
            if (pki.packageName.equals(packageName))
                return true;

        }
        return false;
    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs
                .getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class
                    .forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass,
                    "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }

        return hasNavigationBar;

    }

    public static int getNavigationBarHeight(Context context) {
        int navigationBarHeight = 0;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0 && checkDeviceHasNavigationBar(context)) {
            navigationBarHeight = rs.getDimensionPixelSize(id);
        }
        return navigationBarHeight;
    }

    /**
     * 将TextView中带中括号的字体高亮
     *
     * @param tvFansDesc
     * @param discountText
     * @param foregroundColor
     * @param textColor
     */
    public static void setTextSpan(TextView tvFansDesc, String discountText, String foregroundColor, String textColor) {
        String textContent = discountText.replace("[", "");
        textContent = textContent.replace("]", "");
        tvFansDesc.setText(textContent);

        SpannableStringBuilder builder = new SpannableStringBuilder(textContent);

        List<String> mHiehLight = getSpliteText(discountText);

        for (String heigh : mHiehLight) {
            int index = discountText.indexOf("[" + heigh + "]");
            int endIndex = index + heigh.length();
            discountText = discountText.replace("[" + heigh + "]", heigh);
//            if (!TextUtils.isEmpty(foregroundColor) && textColor.length() == 6){
//                tvFansDesc.setBackgroundColor(Color.parseColor("#"+foregroundColor));
//            }else {
//                tvFansDesc.setBackgroundColor(Color.parseColor("#e646b5ba"));
//            }
            if (!TextUtils.isEmpty(foregroundColor) && textColor.length() == 6)
                builder.setSpan(new ForegroundColorSpan(Color.parseColor("#" + foregroundColor)), index, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!TextUtils.isEmpty(textColor) && textColor.length() == 6)
            tvFansDesc.setTextColor(Color.parseColor("#" + textColor));

        if (mHiehLight.size() > 0) {
            tvFansDesc.setText(builder);
        }
    }

    /**
     * 替换左右标识字符
     *
     * @param text
     * @return
     */
    private static List<String> getSpliteText(String text) {
        List<String> mList = new ArrayList<>();
        text = text.replace("[", "(left)");
        text = text.replace("]", "(right)");
        if (!TextUtils.isEmpty(text) && text.contains("(left)") && text.contains("(right)")) {
            String spli = "";
            String[] strings = text.split("(left)");
            if (null != strings && strings.length > 1) {
                for (int i = 1; i < strings.length; i++) {
                    String result = strings[i].split("(right)")[0];
                    if (result.contains("(")) {
                        result = result.replace("(", "");
                    }
                    if (result.contains(")")) {
                        result = result.replace(")", "");
                    }
                    mList.add(result);
                }
            }
        }
        return mList;
    }

    /**
     * 获取背景色
     *
     * @param type
     * @param color
     * @return
     */
    private static String getBackGroundColor(int type, String color) {
        switch (type) {
            case 1:
                // 限时折扣
                return "#e6" + color;
            case 0:
                //一口价
                return "#e6" + color;
        }
        return "";
    }

    /**
     * 返回字符串的宽高
     *
     * @param str
     * @return
     */
    public static int[] getStringWidth(String str) {
        int[] num = new int[2];
        Paint pFont = new Paint();
        Rect rect = new Rect();
        pFont.getTextBounds(str, 0, str.length(), rect);
        num[0] = rect.width();
        num[1] = rect.height();

        return num;
    }

    /***
     * 判断 是否是奇数
     *
     * @param count
     * @return
     */
    public static boolean isOdd(int count) {
        return count % 2 != 0;
    }

    /***
     * 跳转到应用市场
     * @param context
     */
    public static void gotoAppStore(Context context){
        try {
            if (isInstallByread("com.tencent.android.qqdownloader")) {
                Uri uri = Uri.parse("market://details?id="
                        + context.getPackageName());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                ComponentName cn = new ComponentName(
                        "com.tencent.android.qqdownloader",
                        "com.tencent.pangu.link.LinkProxyActivity");
                intent.setComponent(cn);
                context.startActivity(intent);
                return;
            }
        } catch (Exception e) {
        }
        try {
            Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
        }
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private static boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
}
